/**
 * 
 */
package cn.edu.cqu.bysj.wm.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

import org.ujmp.core.Matrix;
import org.ujmp.core.MatrixFactory;
import org.ujmp.core.enums.ValueType;
import org.ujmp.core.exceptions.MatrixException;

import cn.edu.cqu.bysj.wm.def.Weight;


/**
 * @author Meng
 * 
 */

public class ImportData {

	public static int n;

	/**
	 * import data from the file path
	 * 
	 * @param filePath
	 * @param weightType
	 * @return matrix
	 */
	public static Matrix importData(String filePath,Weight weightType) {


		// to get n1,n2,and n
		StringTokenizer st = new StringTokenizer(filePath, "-");
		@SuppressWarnings("unused")
		String aString = st.nextToken();
		@SuppressWarnings("unused")
		String bString = st.nextToken();
		int n1 = Integer.parseInt(st.nextToken());
		int n2 = Integer.parseInt(st.nextToken());
		n=n2-n1+1;
		
		Matrix matrix = MatrixFactory.sparse(ValueType.INT, n, n);
		
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(filePath));
			String str = "";
			while ((str = in.readLine()) != null) {
				if (str.startsWith("#"))
					continue;
				String[] line = str.split("\t");
				int weight = 1;

				// weighted graph
				if (weightType.equals(Weight.WEIGHTED)) {
					weight = Integer.parseInt(line[2]);
				}
				matrix.setAsInt(weight, Integer.parseInt(line[0]) - n1,
						Integer.parseInt(line[1]) - n1);
				if (weightType.equals(Weight.WEIGHTED)) {
					matrix.setAsInt(weight, Integer.parseInt(line[1]) - n1,
					Integer.parseInt(line[0]) - n1);
				}
			}
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (MatrixException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return matrix;
	}

}
